<?php
class User_cp extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $logged_in = $this->session->userdata('is_logged_in');
        if (!isset($logged_in) || $logged_in != TRUE || empty($logged_in)) //If user has logged in
            die('You do not have permission to access this page. <a href="' . site_url() . '">Home</a>');

        $this->file_type = 'txt|html|htm|doc';
        $this->image_type = 'jpg|jpeg|gif|png';
    }

    public function index()
    {
        $username = $this->session->userdata('username');
        $userid = $this->session->userdata('userid');
        $file_query = $this->db->query("SELECT * FROM `file_info`
                                        WHERE `file_owner_username` = '$username'
                                        ORDER BY `file_id` DESC");

        $data['m_data']['file_query'] = $file_query;

        $user_query = $this->db->query("SELECT * FROM `user_info`
                                        WHERE `id` = '$userid' LIMIT 1");
        $data['m_data']['user_query'] = $user_query;

        if ($this->session->userdata('user_type') == '1') //ADMIN
        {
            $admin_user_query = $this->db->query("SELECT * FROM `user_info` ORDER BY `approved` ASC");
            $data['m_data']['admin_user_query'] = $admin_user_query;

            $admin_file_query = $this->db->query("SELECT * FROM `file_info` ORDER BY `file_approved` ASC, `file_name` ASC");
            $data['m_data']['admin_file_query'] = $admin_file_query;

            $admin_image_query = $this->db->query("SELECT * FROM `image_info` ORDER BY `approved` ASC");
            $data['m_data']['admin_image_query'] = $admin_image_query;

            $admin_stopword_query = $this->db->query("SELECT * FROM `stopword` ORDER BY `date` DESC,`word` ");
            $data['m_data']['admin_stopword_query'] = $admin_stopword_query;

            $admin_stemword_query = $this->db->query("SELECT * FROM `stemword` ORDER BY `isroot` DESC,`word` ASC ");
            $data['m_data']['admin_stemword_query'] = $admin_stemword_query;

            $admin_comp_query = $this->db->query("SELECT * FROM `complain` ORDER BY `read` ASC,`date` DESC ");
            $data['m_data']['admin_comp_query'] = $admin_comp_query;
        }

        //Load user control panel view
        $data['main_content'] = 'usercp_view';
        $data['h_data']['page_title'] = 'User Control Panel';
        $data['h_data']['_css'] = '<link href="' . base_url() . 'css/user_cp.css" rel="stylesheet" type="text/css" />';
        $this->load->view('includes/template', $data);
    }

    public function upload_file()
    {
        $this->load->model('file_model');
        $key = $this->input->post('file_keywords');
        $permission = $this->input->post('file_permission');
        if ($this->input->post('file_upload')) {
            if (empty($key)) {
                die('Keyword can not be empty.');
            }
            $query = $this->file_model->do_upload($key, $permission, $this->file_type, 0);
            if ($query) {
                echo 'SUCCESS';
            } else {
                die('Error occurs');
            }
            $returnTo = 'cp_upload';

        }
        else if ($this->input->post('image_upload')) {
            $query = $this->file_model->do_upload($key, $permission, $this->image_type, 1);
            if ($query) {
                echo 'SUCCESS';
            } else {
                die('Error occurs');
            }
            $returnTo = 'cp_upload_img';
        }
        else
        {
            die('Error occurs');
        }
        echo '  <br/>
                <a href="' . site_url('user_cp?action=' . $returnTo) . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=' . $returnTo) . '"
                }, 10000);
                </script>';
    }

    public function update_file()
    {
        $this->load->model('file_model');
        if ($this->input->post('file_upload')) {
            $keywords = $this->input->post('file_keywords');
            $id = $this->input->post('file_id');
            $permission = $this->input->post('file_permission');

            $this->file_model->do_upload($keywords, $permission, TRUE, TRUE, $id);
            if ($this->db->affected_row()) {
                echo 'SUCCESS';
            } else {
                echo 'Failed';
            }

        }
        else
        {
            die('Error occurs');
        }
        echo '  <br/>
                <a href="' . site_url('user_cp?action=cp_editFile') . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=cp_editFile') . '"
                }, 10000);
                </script>';
    }

    public function manage_user()
    {
        if ($this->session->userdata('user_type') != '1')
            die('This is a admin only area!');
        $action = $this->uri->segment(3);
        $uid = $this->uri->segment(4);
        if (empty($action) || empty($uid))
            die('Undefined Action or User!');

        $this->load->model('member_model');
        switch ($action) {
            case 1: //Approve user.
                if ($this->member_model->approve_user($uid)) {
                    echo 'Successfully approved user!';
                } else {
                    echo '<h2>Fail to approved user.</h2>
                            <p>User id not found or user already approved</p>';
                }
                echo '  <br/>
                        <a href="' . site_url('user_cp?action=cp_manaUser') . '">Redirect in 10 seconds.</a>
                        <script type="text/javascript">
                        setTimeout(function() {
                            window.location = "' . site_url('user_cp?action=cp_manaUser') . '"
                        }, 10000);
                        </script>';
                break;
            case 2: //Remove User
                if ($this->member_model->remove_user($uid)) {
                    echo 'Successfully removed user!';
                } else {
                    echo '<h2>Fail to remove user.</h2>
                            <p>User id not found user already removed</p>';
                }
                echo '  <br/>
                        <a href="' . site_url('user_cp?action=cp_manaUser') . '">Redirect in 10 seconds.</a>
                        <script type="text/javascript">
                        setTimeout(function() {
                            window.location = "' . site_url('user_cp?action=cp_manaUser') . '"
                        }, 10000);
                        </script>';
                break;
            default:
                die('Undefined Action!');
                break;
        }
    }

    public function manage_file()
    {
        if ($this->session->userdata('user_type') != '1')
            die('This is a admin only area!');
        $action = $this->uri->segment(3);
        $type = $this->uri->segment(4);
        $id = $this->uri->segment(5);
        if (empty($action) || empty($id) || empty($type))
            die('Undefined Action or User!');

        $this->load->model('file_model');
        switch ($action) {
            case 1: //Approve user.
                if ($this->file_model->approve_file($id, $type)) {
                    echo 'Successfully approved file!';
                } else {
                    echo '<h2>Fail to approved file.</h2>
                            <p>file id not found or user already approved</p>';
                }
                echo '  <br/>
                        <a href="' . site_url('user_cp?action=cp_manaFile') . '">Redirect in 10 seconds.</a>
                        <script type="text/javascript">
                        setTimeout(function() {
                            window.location = "' . site_url('user_cp?action=cp_manaFile') . '"
                        }, 10000);
                        </script>';
                break;
            case 2: //Remove User
                if ($this->file_model->remove_file($id, $type)) {
                    echo 'Successfully removed file!';
                } else {
                    echo '<h2>Fail to remove file.</h2>
                            <p>File id not found user already removed</p>';
                }
                echo '  <br/>
                        <a href="' . site_url('user_cp?action=cp_manaFile') . '">Redirect in 10 seconds.</a>
                        <script type="text/javascript">
                        setTimeout(function() {
                            window.location = "' . site_url('user_cp?action=cp_manaFile') . '"
                        }, 10000);
                        </script>';
                break;
            default:
                die('Undefined Action!');
                break;
        }
    }

    public function remove_stopword()
    {
        $word = $this->uri->segment(3);
        $this->db->query("DELETE FROM `stopword` WHERE `word`= '$word' LIMIT 1");
        if ($this->db->affected_rows()) {
            echo 'Successfully removed word!';
        } else {
            echo 'Word not found in database.';
        }


        echo '  <br/>
                <a href="' . site_url('user_cp?action=cp_ssword') . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=cp_ssword') . '"
                }, 10000);
                </script>';
    }

    public function add_stopword()
    {
        $word = $this->input->post('stopword');
        if (empty($word)) {
            echo 'Stop word can not be empty.';
        } else {
            $this->db->insert('stopword', array('word' => $word));
            if ($this->db->affected_rows()) {
                echo 'Stop word successfully added.';
            } else {
                echo 'Fail to add stop words, word already exists.';
            }
        }
        echo '  <br/>
                <a href="' . site_url('user_cp?action=cp_ssword') . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=cp_ssword') . '"
                }, 10000);
                </script>';
    }

    public function add_stemword()
    {
        $isrepeat = false;
        $word = $this->input->post('stemword');
        $isroot = $this->input->post('isroot');
        $root = $this->input->post('root');
        if (empty($word)) {
            echo 'Stop word can not be empty.';
        } else {
            if ($this->db->query("SELECT `word` FROM `stemword` WHERE `word` = '$word'")->num_rows() > 0) {
                $isrepeat = true;
            } elseif ($isroot == '1') {
                $this->db->insert('stemword', array('word' => $word, 'isroot' => $isroot));
            } else {
                if ($this->db->query("SELECT `word` FROM `stemword` WHERE `word` = '$root'")->num_rows() == 1) {
                    $this->db->insert('stemword', array('word' => $word, 'isroot' => '0', 'belong' => $root));
                    echo 'Successfully added to the database. <br\>';
                } else {
                    $this->db->insert('stemword', array('word' => $root, 'isroot' => '1')); //Add the root word
                    if ($this->db->affected_rows()) { //If root word successful added
                        $this->db->insert('stemword', array('word' => $word, 'isroot' => '0', 'belong' => $root));
                    } else {
                        echo 'Root word insertion failed. <br\>';
                    }
                }

            }
            if ($this->db->affected_rows() && !$isrepeat) {
                echo 'Stemming word successfully added.';
            } else {
                echo 'Fail to add Stemming words, word already exists.';
            }
        }
        echo '  <br/>
                <a href="' . site_url('user_cp?action=cp_ssword') . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=cp_ssword') . '"
                }, 10000);
                </script>';
    }

    public function remove_stemword()
    {
        $word = $this->uri->segment(3);
        $query = $this->db->query("SELECT * FROM `stemword` WHERE `word` = '$word' LIMIT 1");
        if ($query->num_rows() == 1) {
            $row = $query->row();
            if ($row->isroot != 1) //If it is not a root word
            {
                //DELETE and DONE
                $this->db->query("DELETE FROM `stemword` WHERE `word` = '$word' LIMIT 1");
            } else {
                //DELETE or Stemming Word then Root word.
                $this->db->query("DELETE FROM `stemword` WHERE `belong` = '$word'");
                $this->db->query("DELETE FROM `stemword` WHERE `word` = '$word' LIMIT 1");
            }
        }
        if ($this->db->affected_rows()) {
            echo 'Successfully removed word!';
        } else {
            echo 'Word not found in database.';
        }


        echo '  <br/>
                <a href="' . site_url('user_cp?action=cp_ssword') . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=cp_ssword') . '"
                }, 10000);
                </script>';
    }

    public function warn_user()
    {
        $toUser = $this->uri->segment(3);
        $comId = $this->uri->segment(4);
        if (empty($toUser) || empty($comId)) {
            echo '<h2>Missing Segments</h2>';
        } else {
            $query = $this->db->query("SELECT * FROM `complain` WHERE `id` = '$comId'");
            $query1 = $this->db->query("SELECT `username` FROM `user_info` WHERE `username` = '$toUser'");
            if ($query->num_rows() == 1 && $query1->num_rows() == 1) {
                $row = $query->row();
                $data = array(
                    'content' => $row->content,
                    'to_user' => $row->to_user,
                    'file_name' => $row->to
                );
                $this->db->insert('message', $data);
                if ($this->db->affected_rows()) {
                    $this->db->query("UPDATE `user_info` SET `point` = `point` - 0.2 WHERE `username` = '$toUser' LIMIT 1");
                    if ($this->db->affected_rows()) {
                        echo '<h2>Success!</h2>User warned and point detected!';
                    } else {
                        echo 'User warned and point not detected!';
                    }
                } else {
                    echo 'Failed to warn user.';
                }
            } else {
                echo 'Complain or user not found in the database!';
            }
        }
        echo '  <br/>
                <a href="' . site_url('user_cp?action=cp_viewComp') . '">Redirect in 10 seconds.</a>
                <script type="text/javascript">
                setTimeout(function() {
                    window.location = "' . site_url('user_cp?action=cp_viewComp') . '"
                }, 10000);
                </script>';
    }
}